package main

import (
	"context"
	"log"
	"time"

	"mcp-server/internal/qdrant"
	"mcp-server/internal/storage"
)

func main() {
	log.Println("=== 存储调试工具 ===")

	// 创建存储配置
	config := &storage.StorageConfig{
		QdrantConfig: &qdrant.Config{
			DataPath: "./knowledge_vectors",
		},
		BatchSize: 100,
		CacheSize: 1000,
	}

	// 创建存储管理器
	manager := storage.NewStorageManager()

	// 初始化存储管理器
	err := manager.Initialize(config)
	if err != nil {
		log.Fatalf("初始化存储管理器失败: %v", err)
	}
	defer manager.Close()

	client := manager.GetClient()
	ctx := context.Background()

	// 检查集合
	log.Println("检查集合状态...")
	exists, err := client.CollectionExists(ctx, "knowledge_base")
	if err != nil {
		log.Printf("检查集合失败: %v", err)
	} else {
		log.Printf("集合 knowledge_base 存在: %v", exists)
	}

	if !exists {
		log.Println("创建测试集合...")
		collectionConfig := &storage.CollectionConfig{
			VectorSize: 768,
			Distance:   "cosine",
			IndexType:  "hnsw",
			IndexParams: map[string]interface{}{
				"m":                   16,
				"ef_construct":        200,
				"full_scan_threshold": 10000,
			},
		}

		err = client.CreateCollection(ctx, "knowledge_base", collectionConfig)
		if err != nil {
			log.Printf("创建集合失败: %v", err)
		} else {
			log.Println("集合创建成功")
		}
	}

	// 测试插入向量
	log.Println("测试插入向量...")
	testVector := &storage.VectorData{
		ID:     "test_vector_001",
		Vector: make([]float32, 768),
		Payload: map[string]interface{}{
			"text":      "这是一个测试向量",
			"source":    "debug_tool",
			"timestamp": time.Now().Format(time.RFC3339),
		},
	}

	// 填充测试向量数据
	for i := range testVector.Vector {
		testVector.Vector[i] = float32(i) * 0.001
	}

	err = client.InsertVector(ctx, "knowledge_base", testVector)
	if err != nil {
		log.Printf("插入向量失败: %v", err)
	} else {
		log.Println("向量插入成功")
	}

	// 检查存储统计
	log.Println("获取存储统计...")
	stats, err := client.GetStorageStats(ctx)
	if err != nil {
		log.Printf("获取统计失败: %v", err)
	} else {
		log.Printf("存储统计: 集合数=%d, 向量数=%d", stats.TotalCollections, stats.TotalVectors)
	}

	// 测试搜索
	log.Println("测试向量搜索...")
	queryVector := make([]float32, 768)
	for i := range queryVector {
		queryVector[i] = float32(i) * 0.001
	}

	searchQuery := &storage.SearchQuery{
		Vector: queryVector,
		Limit:  5,
		Filter: nil,
	}
	results, err := client.SearchVectors(ctx, "knowledge_base", searchQuery)
	if err != nil {
		log.Printf("搜索失败: %v", err)
	} else {
		log.Printf("搜索结果: 找到 %d 个匹配", len(results.Hits))
		for i, result := range results.Hits {
			log.Printf("  结果 %d: ID=%s, 相似度=%.4f", i+1, result.ID, result.Score)
		}
	}

	log.Println("调试完成")
}
